#include <asm-generic/errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

typedef struct {
    char name[20];
    int age;
}Person;

typedef struct {
    long type;
    Person person;
}Msg;

void printMsg(Msg *msg) {
    printf("{ type = %ld, name = %s, age = %d }\n",
           msg->type, msg->person.name, msg->person.age);
}

int main(int argc,char *argv[]){
  if(argc < 2){
    printf("Usage: %s <type>",argv[0]);
    return -1;
  }

  // 获取消息的类型
  long type = atol(argv[1]);

  // 传入key值，获取ipc内核对象id
  int id = msgget(0x8888,0);

  Msg msg;
  int res;

  for(;;){
    // 以非阻塞的方式接收类型为type的消息
    res = msgrcv(id,&msg,sizeof(Person),type,IPC_NOWAIT);
    if(res < 0){
      if(errno == ENOMSG){
        printf("no message!\n");
        break;
      }
    }
    printMsg(&msg);
  }

}
  
